
import React, { useState, useEffect, Fragment } from 'react';
import { useHistory } from 'react-router-dom'
import { List } from 'react-virtualized';
import styles from './index.module.scss';
import Search from '../../components/Search';
import HouseItem from '../../components/HouseItem';
import { getHouseList, getHouses } from '../../api';
import { filterTabs, baseCityId } from '../../constans/found';
import { PickerView, Icon } from 'antd-mobile';
const Found = () => {
  const [houseList, setHouseList] = useState([]);
  const [activeIndex, setActiveIndex] = useState(-1);
  const [pickerViewData, setPickerView] = useState([]);
  const [filterData, setFilterData] = useState([[], [], [], []]);
  const history = useHistory();
  useEffect(() => {
    getConditionData()
  }, [])
  const getConditionData = async () => {
    // 房源筛选数据准备
    let pickerViewData = [];
    // 解构出房源筛选数据
    const {
      area,             // 区域
      subway,           // 地铁
      rentType,         // 方式
      price,            // 租金
      roomType,         // 户型
      oriented,         // 朝向
      floor,            // 楼层
      characteristic,   // 房屋亮点
    } = await getHouses()

    // 索引0 PickerView 的数据 - 区域 和 地铁
    pickerViewData[0] = [area, subway];
    // 索引1 PickerView 的数据 - 租房方式
    pickerViewData[1] = rentType;
    // 索引2 PickerView 的数据 - 租金
    pickerViewData[2] = price;
    // 索引3 PickerView 的数据 - 更多筛选
    pickerViewData[3] = [
      { title: '户型', list: roomType },
      { title: '朝向', list: oriented },
      { title: '楼层', list: floor },
      { title: '房屋亮点', list: characteristic },
    ];

    setPickerView(pickerViewData)

  };
  const getHouseListParams = () => {
    const key = filterData[0][0] || 'none';
    console.log(filterData[0][2]);
    const value = ['null', undefined].includes(filterData[0][2]) ? filterData[0][1] : filterData[0][2];
    const params = {
      [key]: value,
      rentType: filterData[1][0],
      price: filterData[2][0],
      more: filterData[3].join(',')
    }
    return params
  }
  const reqHouseList = async () => {
    let params = getHouseListParams();
    params.cityId = baseCityId;
    const { list: houseList } = await getHouseList();
    setActiveIndex(-1)
    setHouseList(houseList);
  }
  const rowRenderer = ({ key, index, style }) => {
    const item = houseList[index];
    return <div key={key} style={style}>
      <HouseItem {...item} />
    </div>
  }
  const onMoreFilterClick = (value) => {
    const arr = [...filterData];
    const index = arr[3].findIndex(v => v === value);
    if (index === -1) {
      arr[3].push(value)
    } else {
      arr[3].splice(index, 1)
    }
    setFilterData(arr)
  }
  const clearFilterData = () => {
    const arr = [...filterData];
    arr[3] = [];
    setFilterData(arr)
  }
  const onPickerViewChange = (value) => {
    const arr = [...filterData]
    arr[activeIndex] = value;
    setFilterData(filterData)
  }
  const renderFilterContent = () => {
    switch (activeIndex) {
      case 0:
      case 1:
      case 2:
        return <div className={styles.filter_content}>
          <div className={styles.filter_content_main}>
            <PickerView
              data={pickerViewData[activeIndex]}
              cols={filterTabs[activeIndex].cols}
              onChange={onPickerViewChange}
              value={filterData[activeIndex]}
            ></PickerView>
          </div>
          <div className={styles.filter_content_buttons}>
            <span className={styles.btn_cancel}>取消</span>
            <span onClick={reqHouseList} className={styles.btn_confirm}>确定</span>
          </div>
        </div>;
      case 3:
        {/* 更多筛选 */ }
        return <div className={styles.filter_more}>
          <div className={styles.filter_more_content}>
            {/* 添加一个判断条件，如果数据还没回来，暂时不渲染右侧更多筛选 */}
            {pickerViewData[3] && pickerViewData[3].map(item =>
              <div key={item.title}>
                <h3 className={styles.filter_more_title}>{item.title}</h3>
                <div className={styles.filter_more_list}>
                  {item.list.map(item2 =>
                    <span
                      key={item2.label}
                      onClick={() => onMoreFilterClick(item2.value)}
                      className={filterData[3].includes(item2.value) ? styles.active : ''}
                    >{item2.label}</span>
                  )}
                </div>
              </div>)}
          </div>
          <div className={styles.filter_content_buttons}>
            <span onClick={clearFilterData} className={styles.btn_cancel}>清除</span>
            <span onClick={reqHouseList} className={styles.btn_confirm}>确定</span>
          </div>
        </div>;
      default:
        return null

    }
  }
  return <Fragment >
    {/* 1.0 页面标题 */}
    <div className={styles.navbar}
    >
      <Icon onClick={() => { history.go(-1); }} className={styles.icon_left} color="#666" type="left"></Icon>
      <Search className={styles.search} />
    </div>
    {/* 2.0 筛选分区 */}
    <div className={styles.filter}>
      {/* 2.1 筛选分区标题部分 */}
      <div className={styles.filter_tabs}>
        {filterTabs.map((item, index) =>
          <span
            className={[styles.filter_tabs_item, activeIndex === index ? styles.active : ''].join(' ')}
            key={item.id}
            onClick={() => { setActiveIndex(index) }}
          >
            {item.title}
            <i className="iconfont icon-arrow"></i>
          </span>
        )}
      </div>
      {/* 2.2 筛选分区内容部分 */}
      {renderFilterContent()}
    </div>
    {/* 3.0 房源列表 - 虚拟化列表 */}
    <div className={styles.houses}>
      <List
        width={window.screen.width}
        height={window.screen.height - 45 - 40 - 50}
        rowCount={houseList.length}   // 大行的长度
        rowHeight={104}                  // 计算大行高度
        rowRenderer={rowRenderer}              // 大行渲染
      />
    </div>
    {/* 4.0 遮罩层 */}
    <div
      className={[styles.mask_bg, activeIndex !== -1 ? styles.mask_show : ''].join(' ')}
      onClick={() => { setActiveIndex(-1) }}
    ></div>
  </Fragment>


}
export default Found